package com.song.mongo.controller;

import com.song.mongo.pojo.User;
import com.song.mongo.service.IUserService;
import com.song.mongo.service.impl.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author TonySong
 * @date 2024/5/16 0016
 * @time 16:11
 */
@Controller //返回一个资源页面
public class UserController {

    @Resource
    private IUserService userService;

//    @GetMapping("/add")
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String toadd(){
        return "add";
    }

//    @PostMapping("/add")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(User user){
        System.out.println("---->"+user);
        this.userService.addUser(user);
        return "redirect:/list";
    }

    @GetMapping("/list")
    public String list(Model model){
        System.out.println("---->list");
        model.addAttribute("users", this.userService.getAllUser());
        return "list";
    }

    @GetMapping("/delete/{id}")
    public @ResponseBody Boolean delete(@PathVariable("id") String id){
        try {
            this.userService.deleteUser(id);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @GetMapping("/update/{id}")
    public String toupdate(@PathVariable("id")String id, Model model){
        model.addAttribute("user", this.userService.getUserById(id));
        return "update";
    }

    @PostMapping("/update/{id}")
    public String toupdate(User user){
       this.userService.updateUser(user);
        return "redirect:/list";
    }
//     public String list(Model model,HttpServletRequest request) {
////     public String list(HttpServletRequest request) {
//        //服务器传值给前端：2种方式
//        //1： 通过request对象
//        // request.setAttribute("name", "张三");
//        //2： 通过model
//        model.addAttribute("name", "张三");
//        request.setAttribute("boy", "男");
//
//        // template+ list+  .html
//         return "list";
//    }
}
